const conn = require("../../libs/DB/Conn");
const _ = require("underscore");
const {createSql, monthTimeRange} = require("./dataAnalysisUtil");
const moment = require("moment");

module.exports = async function(params){
    let time = monthTimeRange(params.rangeId)
    let sql = createSql(params.type,params.userDomainId,time.type,time.range,{type:"range",query:"total"},time.ids,time.groupType);

    let result = await conn(sql.sql,sql.queryIds);
    if(time.type === "month"){
        let rangeGroup = _.groupBy(result,"rangeId");
        let chartObj = {
            xAxis:[],
            data:[{
                name:"本月",
                data:[],
            },{
                name:"去年本月",
                data:[],
            },{
                name:"上个月",
                data:[],
            }]
        }
        let downDropList = [{label:"全部",value:0}]
        for(const rangeId in rangeGroup){
            let rangeData = rangeGroup[rangeId];
            downDropList.push({
                label:rangeData[0].rangeName,
                value:rangeId
            })
            let dataTypeGroup = _.groupBy(rangeData,"dataTime");
            chartObj.xAxis.push(rangeData[0].rangeName);
            chartObj.data[0].data.push(dataTypeGroup[time.dateGroupType[0]] ? dataTypeGroup[time.dateGroupType[0]][0].consumption : "-");
            chartObj.data[1].data.push(dataTypeGroup[time.dateGroupType[1]] ? dataTypeGroup[time.dateGroupType[1]][0].consumption : "-");
            chartObj.data[2].data.push(dataTypeGroup[time.dateGroupType[2]] ? dataTypeGroup[time.dateGroupType[2]][0].consumption : "-");
        }
        return {success:true,chartObj:chartObj,downDropList:downDropList}
    }else{
        let dataTimeGroup = _.groupBy(result,"dataTimeGroup");
        let chartObj = {
            xAxis:[],
            data:[{
                name:"今日",
                data:[],
            },{
                name:"去年今日",
                data:[],
            }]
        }
        for(const month in time.dateGroupType){
            let dataList = [];
            let dateRangeData = _.groupBy(dataTimeGroup[month],"dataTime");
            for(const date of time.dateGroupType[month]){
                dataList.push(dateRangeData[date] ? dateRangeData[date][0].consumption : "-")
            }
            if(month === moment().format("YYYY-MM")){
                chartObj.data[0].data = dataList;
                chartObj.xAxis = time.dateGroupType[month];
            }else{
                chartObj.data[1].data = dataList;
            }
        }
        return {success:true,chartObj:chartObj};
    }
}